package com.up.jiasai.modules.common.controller;
import com.up.vms.application.base.utils.JsonUtils;
import com.up.vms.application.common.utils.json.JsonResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义错误页面返回信息
 * 如果过滤器等出现错误也会回调这里
 * 如果404，403等页面错误
 */
@RestController
public class CustomErrorController implements ErrorController {
    private Log logger = LogFactory.getLog(getClass());
    private static final String ERROR_PATH = "/error";
    @Autowired
    private ErrorAttributes errorAttributes;
    @RequestMapping(ERROR_PATH)
    public JsonResult error(HttpServletRequest request, HttpServletResponse response) {
        JsonResult result = new JsonResult(false);
        WebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> body = this.errorAttributes.getErrorAttributes(webRequest, true);
        Object status = request.getAttribute("javax.servlet.error.status_code");
        String statusStr = String.valueOf(status);
        result.setStatus(statusStr);
        result.setMsg("error");
        if ("403".equals(statusStr)) {
            result.setMsg("权限错误:403");
        } else if ("404".equals(statusStr)) {
            result.setStatus("404");
            result.setMsg("找不到该接口:404");
        } else if ("500".equals(statusStr)) {
            result.setMsg("对不起！服务器趴窝了:500");
        }
        response.setStatus(200);
        result.setMsg(result.getMsg()+">>>body信息:"+ JsonUtils.toStringNoEx(body));
        String url = request.getRequestURI() + "?" + request.getQueryString();
        logger.error("发生了异常>>>>[" + url + "]: " + result.getMsg());
        return result;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
